<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Request;
use think\Db;
use app\common\user\Uservalidate as Validate;

/**
 * 会员接口
 */
class User extends Api
{
    private $appid = 'wx2bab6cd1400f48bb';
    private $secret = '2c4eec8b958e7be9c627ac1f369663de';
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 帐号和密码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $params = $this->request->post();
        if (!$params['account'] || !$params['password']) {
            $this->error('请填写完整信息');
        }

        // 验证手机号格式
        if (!preg_match("/^1[3-9]\d{9}$/", $params['account'])) {
            $this->error('手机号格式不正确');
        }

        $user = Db::name('user')->where('mobile', $params['account'])->find();
        if (!$user) {
            $this->error('账号不存在');
        }

        if ($user['password'] !== md5(md5($params['password']) . $user['salt'])) {
            $this->error('密码错误');
        }

        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $authorization=\app\admin\model\User::setApiToken($user);
            $data = ['userinfo' => $this->auth->getUserinfo(),'authorization'=>$authorization];
            $this->success(__('成功登陆'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile =$this->request->post('phone');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('验证码错误'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $authorization=\app\admin\model\User::setApiToken($user);
            $data = ['userinfo' => $this->auth->getUserinfo(),'authorization'=>$authorization];
            $this->success(__('成功登陆'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile =$this->request->post('phone');
        $code = $this->request->post('verificationCode');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('验证码错误'));
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('参数不合法'));
        }
        $this->auth->logout();
        $this->success(__('成功退出'));
    }

    /**
     * 保存用户信息
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function save(Request $request)
    {
        $data = $request->post();
        $params = $this->request->post();


        if (!$data["mobile"]) {
            $this->error('手机号或密码不能为空');
        }

        // 验证手机号格式
        if (!preg_match("/^1[3-9]\d{9}$/", $data['mobile'])) {
            $this->error('手机号格式不正确');
        }

        // 验证验证码
        $result = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$result) {
            $this->error(__('验证码错误'));
        }

        $user = Db::name('user')->where('mobile', $data["mobile"])->find();
        if (!$user) {
            $this->error('账号不存在');
        }

        // 验证数据（可根据实际需求添加更多验证规则）
//        $validate = $this->validate($data, [
//            'name' => 'require',
//            'gender' => 'require',
//            'birthdate' => 'require',
//            'residence' => 'require',
//            'interests' => 'array'
//        ]);

//        if ($validate !== true) {
//            return json(['code' => 0, 'msg' => $validate]);
//        }

        try {
            // 保存用户信息到数据库
            $salt = random_str(6);
            $user =new \app\admin\model\User();
            $user->username = $data['name'];
            $user->mobile=$data['mobile'];
            $user->gender = $data['gender']=="男"?1:0;
            $user->birthday = $data['birthdate'];
            $user->residence = $data['residence'];
            $user->password = md5($data['password'] . $salt);
            $user->avatar = '/assets/img/avatar.png';
            $user->group_id=1;
            $user->salt = $salt;
            $user->status = 1;
            $user->createtime = time();
            $user->jointime = time();
            $user->interests = implode(',', $data['interests']);
            Db::name('user')->where('mobile', $user['mobile'])->update($user->toArray());

            return json(['code' => 200, 'msg' => '保存成功']);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '保存失败：' . $e->getMessage()]);
        }
    }

    /**
     * 学员注册
     */
    public function studentRegister()
    {
        $params = $this->request->post();

        if (!$params['phone'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        if (!preg_match("/^1[3-9]\d{9}$/", $params['phone'])) {
            $this->error('手机号格式不正确');
        }

        if ($params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
        $cache_code = cache('student_register_code_' . $params['phone']);
        if (!$cache_code || $cache_code != $params['code']) {
            $this->error('验证码错误或已过期');
        }

        if (Db::name('user')->where('mobile', $params['phone'])->find()) {
            $this->error('该手机号已注册');
        }

        $salt = random_str(6);
        $data = [
            'mobile' => $params['phone'],
            'username' => 'XY' . $params['phone'], // 学员前缀
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 1, // 学员
            'createtime' => time(),
            'jointime' => time()
        ];

        try {
            $user_id = Db::name('user')->insertGetId($data);
            cache('student_register_code_' . $params['phone'], null);
            $this->success('注册成功', ['id' => $user_id]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 教师注册
     */
    public function teacherRegister()
    {
        $params = $this->request->post();

        if (!$params['phone'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        if (!preg_match("/^1[3-9]\d{9}$/", $params['phone'])) {
            $this->error('手机号格式不正确');
        }

        if ($params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
        $result = Sms::check($params['phone'], $params['code'], 'register');
        if (!$result) {
            $this->error(__('验证码错误'));
        }

        if (Db::name('user')->where('phone', $params['phone'])->find()) {
            $this->error('该手机号已注册');
        }

        $salt = random_str(6);
        $data = [
            'mobile' => $params['phone'],
            'username' => 'JS' . $params['phone'],
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 2, // 教师
            'createtime' => time(),
            'jointime' => time()
        ];

        try {
            $user_id = Db::name('user')->insertGetId($data);
            Sms::flush( $params['mobile'], 'register');
            $this->success('注册成功', ['id' => $user_id]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function adminRegister()
    {
        $params = $this->request->post();

        if (!$params["username"] || !$params["mobile"]) {
            $this->error("请填写完整信息");
        }

        if (!$params['mobile'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        // 验证手机号格式
        if (!preg_match("/^1[3-9]\d{9}$/", $params['mobile'])) {
            $this->error('手机号格式不正确');
        }

        // 验证两次密码是否一致
        if ($params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
        $result = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$result) {
            $this->error(__('验证码错误'));
        }

        // 检查手机号是否已注册
        if (Db::name('user')->where('mobile', $params['mobile'])->find()) {
            $this->error('该手机号已注册');
        }


        $salt = random_str(6);
        $data = [
            'mobile' => $params['mobile'],
            'username' => 'GLY' . $params['mobile'],
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 3, // 管理员
            'createtime' => time(),
            'jointime' => time(),
            "gender" => intval($params["gender"] ?? 0),
            "birthday" => $params["birthday"] ? strtotime($params["birthday"]) : null,
            "party" => intval($params["party"] ?? 0),
            "updatetime" => time(),
        ];


        // 检查手机号是否已存在
        $exists = Db::name("user")->where("mobile", $params["mobile"])->find();

        try {
            if ($exists) {
                // 更新
                Db::name("user")->where("id", $exists["id"])->update($data);
                $user_id = $exists["id"];
                $data["id"]=$user_id;
            } else {
                // 新增
                $data["createtime"] = time();
                $data["jointime"] = time();
                $user_id = Db::name("user")->insertGetId($data);
                $data["id"]=$user_id;
            }
            Sms::flush( $params['mobile'], 'register');
            $data=array("code"=>1,"msg"=>"保存成功","data"=>$data);
            echo json_encode($data);exit;
        } catch (\Exception $e) {
            $this->error();
        }
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('用户名已经存在'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('昵称已经存在'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user["uid"])->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        \app\common\model\User::where('id', $user["uid"])->update(['email' => $email]);
        Ems::flush($email, 'changeemail');
        $this->success("更改成功！");
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {

        $user = $this->auth->getUser();
        $mobile =$this->request->post('phone');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('成功登陆'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function updateUserInfo()
    {
        $params = $this->request->post();
        $user = $this->auth->getUser();
        $data = [
            'nickname' => $params['nickName'],
            'avatar' => $params['avatarUrl'],
            'mobile' => $params['phoneCode'],
            'openid' => $params['openid'],
            'updatetime' => time(),
        ];
        if($params['phoneCode']!=""){
            $data['username']=$params['phoneCode'];
        }

        model("app\admin\model\User")->where("openid","=",$params["openid"])->update($data);
        $this->success();
    }

    /**
     * 获取微信登录code
     * @ApiMethod (GET)
     */
    public function getWxLoginCode()
    {
        $appid = $this->appid; // 你的微信小程序appid
        $redirect_uri = urlencode('https://ys.yangjc.com/api/user/wxlogin'); // 回调地址
        $scope = 'snsapi_userinfo'; // 授权作用域

        // 构造微信授权URL
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";

        // 重定向到微信授权页面
        header("Location: {$url}");
        exit;
    }
}
